/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.LinkedList;

/**
 *
 */
public class DBConnectionPool implements DBConfig
{
    private LinkedList<Connection> connections = new LinkedList<Connection>();
    private final int MAX_CONNECTIONS = 150;
    private int numConnections = 0;
    
    //create class as singleton:
    private static DBConnectionPool theInstance = null;
    public static DBConnectionPool getInstance() throws ClassNotFoundException
    {
        if(theInstance == null)
            theInstance = new DBConnectionPool();
        return theInstance;
    }
    
    private DBConnectionPool() throws ClassNotFoundException
    {
        Class.forName(DB_DRIVER);
    }
    
    public Connection getConnection() throws Exception
    {
        if(numConnections >= MAX_CONNECTIONS)
        {
            throw new Exception("Connection limit reached.");
        }
        if(connections.isEmpty())
        {
            Connection con = DriverManager.getConnection(DB_URL+DB_NAME, DB_USER, DB_PASSWD);
            return con;
        }
        numConnections++;
        return connections.poll();
    }
    
    public void releaseConnection(Connection con)
    {
        connections.offer(con);
    }
}
